package com.sywb.chuangyebao.contract;

import android.app.Activity;
import android.content.Context;
import android.media.MediaPlayer;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.util.LongSparseArray;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.czt.mp3recorder.MP3Player;
import com.sywb.chuangyebao.Constants;
import com.sywb.chuangyebao.R;
import com.sywb.chuangyebao.bean.InterestIndustryInfo;
import com.sywb.chuangyebao.bean.NewsOwner;
import com.sywb.chuangyebao.bean.Page;
import com.sywb.chuangyebao.bean.Question;
import com.sywb.chuangyebao.bean.SuperInfo;
import com.sywb.chuangyebao.bean.User;
import com.sywb.chuangyebao.utils.DateTimeUtils;
import com.sywb.chuangyebao.utils.GlideUtils;
import com.sywb.chuangyebao.utils.HttpCallback;
import com.sywb.chuangyebao.utils.HttpUtils;
import com.sywb.chuangyebao.utils.RegexUtils;
import com.sywb.chuangyebao.utils.Utils;
import com.sywb.chuangyebao.view.QAndADetailActivity;
import com.sywb.chuangyebao.view.TopicActivity;
import com.sywb.chuangyebao.widget.RichTextView;

import org.bining.footstone.adapter.BaseRecyclerAdapter;
import org.bining.footstone.adapter.BaseRecyclerMultiItemAdapter;
import org.bining.footstone.adapter.ViewHolderHelper;
import org.bining.footstone.adapter.listener.OnItemChildClickListener;
import org.bining.footstone.adapter.listener.OnItemClickListener;
import org.bining.footstone.db.DbManager;
import org.bining.footstone.log.Logger;
import org.bining.footstone.rxjava.rxbus.RxBus;
import org.bining.footstone.utils.ToastUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public interface BaseQuestionContract {

    interface BaseQuestionView extends BaseRefreshContract.View {
    }

    abstract class Presenter<T extends BaseQuestionView> extends BaseRefreshContract.Presenter<T> {

        protected QuestionAdapter recyclerAdapter;
        protected TutorAdapter adapter;
        protected int category;
        protected int topic_id;
        protected int pageNo = 1;
        protected LongSparseArray<String> categories;
        protected String categoryName;
        private Question currentAudioQuestion;

        @Override
        public void onStart() {
            super.onStart();
            recyclerAdapter = new QuestionAdapter(mContext);
            setRecyclerAdapter(recyclerAdapter);
            adapter = new TutorAdapter(mActivity);
            adapter.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(View view, int i) {
//                    mView.advance(UserIndexActivity.class, adapter.getItem(i).user_id);
                    Utils.goUserIndex(mView, adapter.getItem(i).user_id);
                }
            });

            if (category > 0) {
                categoryName = DbManager.getInstance().queryById(category, InterestIndustryInfo.class).name;
            } else if (categories == null) {
                categories = new LongSparseArray<>();
            }
        }

        @Override
        public void onStartRefresh() {
            pageNo = 1;
            listQuestions();
        }

        @Override
        public void onStartLoadMore() {
            pageNo++;
            listQuestions();
        }

        public void listQuestions() {
            HttpUtils.listQuestions(category, 0, topic_id, pageNo, new HttpCallback<Page<Question>>() {

                @Override
                public void onSuccess(Page<Question> questionPage) {

                    if (questionPage.list != null) {
                        for (Question question : questionPage.list) {
                            question.setItemType();
                            question.setTopic();
                            int categoryId = question.category_id;
                            if (category > 0) {
                                question.categoryName = categoryName;
                            } else if (!TextUtils.isEmpty(categories.get(categoryId))) {
                                question.categoryName = categories.get(categoryId);
                            } else {
                                InterestIndustryInfo info = DbManager.getInstance().queryById(categoryId, InterestIndustryInfo.class);
                                if (info != null) {
                                    question.categoryName = info.name;
                                    categories.put(categoryId, question.categoryName);
                                }
                            }
                        }
                    }

                    if (pageNo == 1) {
                        onEndRefresh();
                        if (questionPage.size > 0) {
                            recyclerAdapter.setFooterView(R.layout.layout_footer);
                            if (questionPage.size >= 3 && mView != null) {
                                listTutors();
                            }
                        } else {
                            recyclerAdapter.setFooterView(null);
                        }
                        recyclerAdapter.clearDatas();
                    }
                    recyclerAdapter.notifyDataChangedAfterLoadMore(questionPage.list);
                }

                @Override
                public void onError(String strMsg) {
                    super.onError(strMsg);
                    if (pageNo == 1) {
                        onEndRefresh();
                    } else {
                        onEndLoadMore();
                    }
                    showMessage(strMsg);
                }

                @Override
                public void onFinish() {
                    super.onFinish();
                    onFinishAsync();
                    isNoData();
                }
            });
        }

        private void listTutors() {
            if (topic_id > 0 || pageNo > 1) {
                return;
            }
            HttpUtils.listUserTutor(category, 5, pageNo, true, Constants.USER_TYPE_TUTOR, 0, "", "", new HttpCallback<Page<User>>() {

                @Override
                public void onSuccess(Page<User> userPage) {
                    if (userPage == null || userPage.size == 0) {
                        return;
                    }
                    if (recyclerAdapter.getDatas() != null && recyclerAdapter.getDatas().size() >= 3) {
                        if (recyclerAdapter.getItem(3).getItemType() == Constants.USER_LIST) {
                            return;
                        }

                        Question question = new Question();
                        question.setItemType(Constants.USER_LIST);
                        question.title = mContext.getResources().getString(R.string.recommend_tutor_star);
                        recyclerAdapter.addData(3, question);
                        adapter.setDatas(userPage.list);
                    }
                }

                @Override
                public void onError(String strMsg) {
                    super.onError(strMsg);
                }

                @Override
                public void onFinish() {
                    super.onFinish();
                    onFinishAsync();
                }
            });
        }

        @Override
        public void onRecyclerItemClick(int i) {
//            if (recyclerAdapter.getDataCount() == 0) {
//                return;
//            }
//
//            if (topic_id > 0) {
//                if (i > 0) {
//                    mView.advance(QAndADetailActivity.class, recyclerAdapter.getItem(i - 1).question_id);
//                }
//            } else {
//                mView.advance(QAndADetailActivity.class, recyclerAdapter.getItem(i).question_id);
//            }

            if (recyclerAdapter.getDataCount() == 0) {
                return;
            }
            mView.advance(QAndADetailActivity.class, recyclerAdapter.getItem(i).question_id);

        }

        @Override
        public boolean useRecyclerDivider() {
            return false;
        }

        class QuestionAdapter extends BaseRecyclerMultiItemAdapter<Question> implements OnItemChildClickListener {

            public QuestionAdapter(Context context) {
                super(context, null);
                addItemType(Constants.QANDA_TEXT, R.layout.item_user_dynamic_text);
                addItemType(Constants.QANDA_PIC_ONE, R.layout.item_user_dynamic_pic_one);
                addItemType(Constants.QANDA_PIC_THREE, R.layout.item_user_dynamic_pic_three);
                addItemType(Constants.QANDA_MEDIA, R.layout.item_user_dynamic_media);
                addItemType(Constants.USER_LIST, R.layout.layout_tutor_recommend);
            }

            @Override
            protected void setMultiData(final ViewHolderHelper viewHolderHelper, final int i, final Question model) {
                viewHolderHelper.setOnItemChildClickListener(this);
                if (model.getItemType() != Constants.USER_LIST) {
                    //包括头部和富文本
                    setHeadPart(viewHolderHelper, i, model);
//                    setBottomPart(viewHolderHelper, model);

                    viewHolderHelper.setItemChildClickListener(R.id.iv_face);
                    viewHolderHelper.setItemChildClickListener(R.id.iv_user_type);
                    viewHolderHelper.setItemChildClickListener(R.id.tv_collection_name);
                    viewHolderHelper.setItemChildClickListener(R.id.tv_collection_time);
                    viewHolderHelper.setItemChildClickListener(R.id.tv_bottom_right);
                    viewHolderHelper.setItemChildClickListener(R.id.richTextView);

                    //设置富文本
                    RichTextView richTextView = viewHolderHelper.getView(R.id.richTextView);

                    switch (model.getItemType()) {
                        case Constants.QANDA_PIC_ONE:
                            viewHolderHelper.setItemChildClickListener(R.id.iv_img);
                            //设置图片（一张）
                            ImageView imageView = viewHolderHelper.getView(R.id.iv_img);
                            GlideUtils.getNormalIamgeToUrl(mActivity, model.pic.get(0), imageView);

                            richTextView.setDeviationDP(R.dimen.dp_172);
                            break;
                        case Constants.QANDA_PIC_THREE:
                            viewHolderHelper.setItemChildClickListener(R.id.iv_img0);
                            viewHolderHelper.setItemChildClickListener(R.id.iv_img1);
                            viewHolderHelper.setItemChildClickListener(R.id.iv_img2);
                            if (model.pic != null && model.pic.size() > 0) {
                                ImageView imageView0 = viewHolderHelper.getView(R.id.iv_img0);
                                GlideUtils.getNormalIamgeToUrl(mActivity, model.pic.get(0), imageView0);

                                ImageView imageView1 = viewHolderHelper.getView(R.id.iv_img1);
                                if (model.pic.size() > 1) {
                                    imageView1.setVisibility(View.VISIBLE);
                                    GlideUtils.getNormalIamgeToUrl(mActivity, model.pic.get(1), imageView1);
                                    ImageView imageView2 = viewHolderHelper.getView(R.id.iv_img2);
                                    if (model.pic.size() > 2) {
                                        imageView2.setVisibility(View.VISIBLE);
                                        GlideUtils.getNormalIamgeToUrl(mActivity, model.pic.get(2), imageView2);
                                    } else {
                                        imageView2.setVisibility(View.INVISIBLE);
                                    }
                                } else {
                                    imageView1.setVisibility(View.INVISIBLE);
                                }
                            }
                            break;
                        case Constants.QANDA_MEDIA:
                            Utils.setQuestionAudioItemView(viewHolderHelper, mActivity, model, playingAudioUrl, mp3Player, isPlaying);
                            break;
                    }


                    richTextView.setRichText(model.title, model.richInfoList);
                    richTextView.setExpandView(true);
                    richTextView.setOnLinkClickListener(new RichTextView.OnLinkClickListener() {
                        @Override
                        public void onAtClick(RichTextView richTextView, Object userId) {
//                            mView.advance(UserIndexActivity.class, userId);
                            Utils.goUserIndex(mView, (Integer) userId);
                        }

                        @Override
                        public void onTopicClick(RichTextView richTextView, Object topicId) {
                            //若当前已为话题聚合页，则不跳转
                            if (topic_id == 0) {
                                mView.advance(TopicActivity.class, topicId);
                            }
                        }

                        @Override
                        public void onEmojiClick(RichTextView richTextView, Object emoji) {

                        }

                        @Override
                        public void onUrlClick(RichTextView richTextView, Object url) {

                        }

                        @Override
                        public void onAllClick(RichTextView richTextView) {

                        }
                    });

                } else {
                    viewHolderHelper.setText(R.id.tv_name, model.title);

                    viewHolderHelper.setItemChildClickListener(R.id.tv_more);

                    RecyclerView recyclerView = viewHolderHelper.getView(R.id.common_recycler);
                    recyclerView.setLayoutManager(new LinearLayoutManager(mActivity, LinearLayoutManager.HORIZONTAL, false));
                    recyclerView.setAdapter(adapter);
                    adapter.notifyDataSetChanged();
                }

            }

            private void setHeadPart(ViewHolderHelper viewHolderHelper, final int i, final Question model) {
                //设置提问人头像
                ImageView imageFace = viewHolderHelper.getView(R.id.iv_face);
                GlideUtils.getCircleImageToUrl(mActivity, model.getShowAvatar(), imageFace, R.drawable.head_image);

//                //设置提问人角色类型
                Utils.setUserRoleIcon((ImageView) viewHolderHelper.getView(R.id.iv_user_type), model.getUserRole());

                //设置提问人名称
                viewHolderHelper.setText(R.id.tv_collection_name, model.getShowName());

                //设置提问时间
                viewHolderHelper.setText(R.id.tv_collection_time, DateTimeUtils.getFormatForMinusMonthDayMinutesSecond(model.create_time));

//                //隐藏头部右边 的 推荐 按钮
                viewHolderHelper.setVisibility(R.id.tv_recommend, View.GONE);

                setBottomPart(viewHolderHelper, model);
            }

            private void setBottomPart(ViewHolderHelper viewHolderHelper, final Question model) {
                TextView recommendView = viewHolderHelper.getView(R.id.tv_recommend_red);
                if (model.isRecommend == 1) {
                    //是推荐的
                    recommendView.setVisibility(View.VISIBLE);
                    //设置回答个数
                    viewHolderHelper.setText(R.id.tv_bottom_left, "   ·   " + RegexUtils.getFormatNum(model.answer_num) + "回答");
                } else {
                    recommendView.setVisibility(View.GONE);
                    viewHolderHelper.setText(R.id.tv_bottom_left, RegexUtils.getFormatNum(model.answer_num) + "回答");
                }

                //设置分类
                viewHolderHelper.setText(R.id.tv_bottom_right, category > 0 ? "" : model.categoryName);
            }

            @Override
            public void onItemChildClick(View view, int i) {
                if (topic_id > 0 && i == 0) {
                    return;
                }

                Question question;
                if (topic_id > 0) {
                    question = mDatas.get(i - 1);
                } else {
                    question = mDatas.get(i);
                }

                switch (view.getId()) {
                    case R.id.iv_face:
                    case R.id.iv_user_type:
                    case R.id.tv_collection_name:
                    case R.id.tv_collection_time:
//                        mView.advance(UserIndexActivity.class, question.user_id);
                        Utils.goUserIndex(mView, question.user_id);
                        break;
                    case R.id.tv_more:
                        //跳到导师列表
                        Logger.e("切换到 导师列表");
                        RxBus.get().post(Constants.TOPIC_TYPE_USER, Constants.TOPIC_TYPE_USER);
                        break;
                    case R.id.tv_bottom_right:
                        //在分类下，不需要切换
                        if (category > 0) {
                            return;
                        }

                        //跳到问答分类列表下的该分类下
                        Logger.e("切换到 " + question.categoryName + " 分类");
                        RxBus.get().post(Constants.POST_LIST_CATEGORY, String.valueOf(question.category_id));

                        //在话题下，关掉当前界面
                        if (topic_id > 0) {
                            mView.exit();
                        }
                        break;
                    case R.id.richTextView:
                        onRecyclerItemClick(i);
                        break;
                    case R.id.iv_media_type:
                        //播放语音
                        currentAudioQuestion = question;
                        playAudio(question.audio);
                        notifyDataSetChanged();
                        break;
                    case R.id.iv_img:
                    case R.id.iv_img0:
                        Utils.goBigPic(mActivity, 0, question.pic);
                        break;
                    case R.id.iv_img1:
                        Utils.goBigPic(mActivity, 1, question.pic);
                        break;
                    case R.id.iv_img2:
                        Utils.goBigPic(mActivity, 2, question.pic);
                        break;
                }
            }


        }


        @Override
        public void onDestroy() {
            super.onDestroy();
            if (mp3Player != null) {
                mp3Player.stopPlay();
                mp3Player = null;
            }
        }

        private MP3Player mp3Player;
        private boolean isPlaying;
        private String playingAudioUrl;

        private void playAudio(String currentAudioUrl) {
            //播放语音
            if (mp3Player == null) {
                mp3Player = MP3Player.getInstance();
                mp3Player.setOnMP3PlayerListener(new MP3Player.OnMP3PlayerListener() {
                    @Override
                    public void onCompletion(MediaPlayer mediaPlayer) {
                        Logger.e("MediaPlayer onCompletion:");
                        currentAudioQuestion.progress = 0;
                        playStop();
                    }

                    @Override
                    public void onSeekComplete(MediaPlayer mediaPlayer) {
                        Logger.e("MediaPlayer onSeekComplete:");
                    }

                    @Override
                    public void onError(MediaPlayer mediaPlayer) {
                        onCompletion(mediaPlayer);
                        showMessage("播放错误,请稍候再试");
                    }
                });

                mp3Player.setOnMP3PlayerStartListener(new MP3Player.onMP3PlayerStartListener() {
                    @Override
                    public void onStart(MediaPlayer mediaPlayer) {
                        Logger.e("duration:" + mp3Player.getMediaPlayer().getDuration());
//                        seekbar.setMax(mp3Player.getMediaPlayer().getDuration());
//                        tvAudioTime.setText(DateTimeUtils.getMediaTimeNumber(seekbar.getMax() / 1000));
                        currentAudioQuestion.max = mp3Player.getMediaPlayer().getDuration();
                        recyclerAdapter.notifyDataSetChanged();
                        startTimer();
                    }
                });

                mp3Player.startPlay(currentAudioUrl, null);
                isPlaying = true;
                playingAudioUrl = currentAudioUrl;
                return;
            }
            Logger.e("是否点击同一个：" + currentAudioUrl.equals(playingAudioUrl) + "是否在播：" + isPlaying);

            if (currentAudioUrl.equals(playingAudioUrl)) {
                if (isPlaying) {
                    mp3Player.pausePlay();
                    playStop();
                } else {
                    mp3Player.restart();
                    isPlaying = true;
                    startTimer();
                }
            } else {
                if (isPlaying) {
                    mp3Player.stopPlay();
                }
                currentAudioQuestion.progress = 0;
                playStop();
                mp3Player.startPlay(currentAudioUrl, null);
                isPlaying = true;
                startTimer();
            }
            playingAudioUrl = currentAudioUrl;
        }

        public void playStop() {
            isPlaying = false;
            if (recyclerAdapter != null) {
                recyclerAdapter.notifyDataSetChanged();
            }
            stopTimer();
        }

        private Timer mTimer;
        private boolean isChanging = false;//互斥变量，防止定时器与SeekBar拖动时进度冲突


        private void startTimer() {
            if (currentAudioQuestion.progress > 0) {
                mp3Player.getMediaPlayer().seekTo(currentAudioQuestion.progress);
            }

            //----------定时器记录播放进度---------//
            isChanging = false;
            mTimer = new Timer();
            TimerTask mTimerTask = new TimerTask() {
                @Override
                public void run() {
                    if (isChanging) {
                        return;
                    }

                    try {
                        if (mp3Player.getMediaPlayer() == null) {
                            return;
                        }

//                        seekbar.setProgress(mp3Player.getMediaPlayer().getCurrentPosition());
                        currentAudioQuestion.progress = mp3Player.getMediaPlayer().getCurrentPosition();

//                        tvCurrentTime.setText(DateTimeUtils.getMediaTimeNumber(seekBar.getProgress() / 1000));
                        mActivity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                recyclerAdapter.notifyDataSetChanged();
                            }
                        });
                        Logger.e("currentPosition:" + mp3Player.getMediaPlayer().getCurrentPosition());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            };
            mTimer.schedule(mTimerTask, 0, 500);
        }


        private void stopTimer() {
            if (mp3Player != null) {
                mp3Player.pause();
            }
            if (mTimer != null) {
                isChanging = true;
                mTimer.cancel();
                Logger.e("stopTimer");
            }
        }


        class TutorAdapter extends BaseRecyclerAdapter<User> implements OnItemChildClickListener {

            TutorAdapter(Activity activity) {
                super(activity, R.layout.item_tutor_recommend);
            }

            @Override
            protected void setItemData(ViewHolderHelper viewHolderHelper, int position, User model) {
                viewHolderHelper.setVisibility(R.id.space_view, position == 0 ? android.view.View.VISIBLE : android.view.View.GONE);

                ImageView imageView = viewHolderHelper.getView(R.id.iv_tutor);
                GlideUtils.getCircleImageToUrl(mActivity, model.avatar, imageView);

//                Utils.setUserRoleIcon((ImageView) viewHolderHelper.getView(R.id.iv_user_type), model.user_role);
                viewHolderHelper.setVisibility(R.id.iv_user_type, false);

                viewHolderHelper.setText(R.id.tv_tutor, model.display_name);
                viewHolderHelper.setText(R.id.tv_tutor_sign, model.getGoodAtString());

                TextView tvAddFocus = viewHolderHelper.getView(R.id.tv_add_focus);
                Utils.setFolllowView(mActivity, model.is_follow, tvAddFocus);

                viewHolderHelper.setText(R.id.tv_add_focus, model.is_follow ? R.string.btn_attentioned : R.string.focus);

                if (!model.is_follow) {
                    viewHolderHelper.setOnItemChildClickListener(this);
                    viewHolderHelper.setItemChildClickListener(R.id.tv_add_focus);
                }
            }

            @Override
            public void onItemChildClick(View view, int i) {
                User user = mDatas.get(i);
                switch (view.getId()) {
                    case R.id.tv_add_focus:
                        //判断是否登录
                        if (!Utils.checkIsLogin()) {
                            return;
                        }
                        HttpUtils.follow(user.user_id, Constants.TOPIC_TYPE_USER, !user.is_follow, new HttpCallback<Object>(i) {

                            @Override
                            public void onStart() {
                                super.onStart();
                                onStartAsync();
                            }

                            @Override
                            public void onFinish() {
                                super.onFinish();
                                onFinishAsync();
                            }

                            @Override
                            public void onSuccess(Object s) {
                                User user = mDatas.get((int) data);
                                ToastUtils.show(mContext, user.is_follow ? "取消关注" : "关注成功");
                                user.is_follow = !user.is_follow;
                                notifyDataSetChanged();
                            }

                            @Override
                            public void onError(String strMsg) {
                                super.onError(strMsg);
                                showMessage(strMsg);
                            }
                        });
                        break;
                }
            }
        }
    }


}

